import os
import re
import time

import pymongo
from pymongo import MongoClient


def get_Save_DB():
    url = "192.168.1.99"
    # url = "localhost"
    port = 27017
    db_name = 'comic_spider_db'
    client = MongoClient(url, port)
    client[db_name].authenticate('xmtj', '0-=p[]P{}', 'admin')
    db = client[db_name]
    return db


mongoSaveDB = get_Save_DB()

mongoSaveIpCollection = mongoSaveDB.all_ip_name
mongoSaveRankCollection = mongoSaveDB.comic_rank
mongoSaveAuthorCollection = mongoSaveDB.all_author_name


def updateAuthor():
    global mongoSaveIpCollection
    global mongoSaveAuthorCollection

    needUpdate = mongoSaveIpCollection.find({'author': re.compile('.*知音漫客.*', re.IGNORECASE)})
    mongoSaveIpCollection.delete_many({'author': re.compile('.*知音漫客.*', re.IGNORECASE)})
    for one in needUpdate:
        print('ip:', one['ip_name'], '  author:', one['author'])
        author = str(one['author'])
        if author != '知音漫客':
            author.replace('知音漫客', '')
        mongoSaveIpCollection.insert({'ip_name': one['ip_name'], 'author': author})
    needUpdateAuthor = mongoSaveAuthorCollection.find({'author': re.compile('.*知音漫客.*', re.IGNORECASE)})
    for one in needUpdateAuthor:
        print('  author:', one['author'])


def checkData():
    global mongoSaveIpCollection
    global mongoSaveAuthorCollection
    global mongoSaveRankCollection
    ranks = mongoSaveRankCollection.find().sort([('score', pymongo.DESCENDING)]).limit(1000)
    for one in ranks:
        author = ''
        try:
            author = one['author']
        except Exception:
            pass
        with open('name.txt', 'a+', encoding='utf-8') as f:
            f.writelines([author, '\n'])


if __name__ == "__main__":
    # updateAuthor()
    os.system('./test.sh')
    # checkData()
